// 中间件的基本格式
// function middleware({ getState, dispatch }) {
//   return (next) => (action) => {
//     const result = next(action);
//     return result;
//   };
// }

import { stdChannel } from './channel';
import runSaga from './runSaga';

export default function createSagaMiddleware() {
  let boundRunSaga;
  let channel = stdChannel();

  function sagaMiddleware({ getState, dispatch }) {
    // 通过bind 来保存 getState, dispatch
    boundRunSaga = runSaga.bind(null, { channel, getState, dispatch });

    return (next) => (action) => {
      const result = next(action);
      channel.put(action);
      return result;
    };
  }

  sagaMiddleware.run = (...arg) => boundRunSaga(...arg);

  return sagaMiddleware;
}
